import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'index.dart';
import '../../../common/utils/index.dart';
import '../../../common/widgets/index.dart';

/// 个人信息编辑页面视图
/// 
/// 显示和编辑用户个人信息
/// 采用简洁的列表式布局
class PeofileDetialPage extends GetView<PeofileDetialController> {
  const PeofileDetialPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    return SingleChildScrollView(
      child: Column(
        children: [
          // 头像区域
          _buildAvatarSection(),
          
          // 信息列表区域
          Container(
            color: Colors.white,
            child: Column(
              children: [
                _buildInfoItem(
                  label: '昵称',
                  value: Obx(() => Text(
                    controller.form.value.nickname,
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  )),
                  onTap: () => _showEditDialog(
                    Get.context!,
                    '编辑昵称',
                    controller.form.value.nickname,
                    (value) => controller.updateLocalNickname(value),
                  ),
                ),
                
                _buildInfoItem(
                  label: '性别',
                  value: Obx(() => Text(
                    controller.form.value.gender,
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  )),
                  onTap: () => _showGenderPicker(Get.context!),
                ),
                
                _buildInfoItem(
                  label: '年龄',
                  value: Obx(() => Text(
                    '${controller.displayAge}岁',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  )),
                  showArrow: false,
                ),
                
                _buildInfoItem(
                  label: '生日',
                  value: Obx(() => Text(
                    controller.form.value.birthday,
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  )),
                  onTap: () => _showDatePicker(Get.context!),
                ),
                
                _buildInfoItem(
                  label: '城市',
                  value: Obx(() => Text(
                    controller.form.value.city,
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  )),
                  onTap: () => _showEditDialog(
                    Get.context!,
                    '编辑城市',
                    controller.form.value.city,
                    (value) => controller.updateLocalCity(value),
                  ),
                ),
                
                _buildInfoItem(
                  label: '签名',
                  value: Obx(() => Text(
                    controller.form.value.signature,
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  )),
                  onTap: () => _showEditDialog(
                    Get.context!,
                    '编辑签名',
                    controller.form.value.signature,
                    (value) => controller.updateLocalSignature(value),
                    maxLines: 3,
                  ),
                ),
                
                _buildInfoItem(
                  label: '常出没地',
                  value: Obx(() => Text(
                    controller.form.value.frequentPlaces,
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  )),
                  onTap: () => _showEditDialog(
                    Get.context!,
                    '编辑常出没地',
                    controller.form.value.frequentPlaces,
                    (value) => controller.updateLocalFrequentPlaces(value),
                  ),
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 10),
          
          // 爱好区域
          _buildHobbiesSection(),
          
          const SizedBox(height: 10),
          
          // 相册区域
          _buildAlbumSection(),
          
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  /// 构建头像区域
  Widget _buildAvatarSection() {
    return Container(
      color: Colors.white,
      child: InkWell(
        onTap: controller.isUploadingAvatar.value ? null : controller.onAvatarTap,
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color: Colors.grey.shade200,
                width: 0.5,
              ),
            ),
          ),
          child: Row(
            children: [
              // 左侧文字
              Text(
                '头像',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.black87,
                ),
              ),
              Expanded(
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Stack(
                    children: [
                      // 头像图片
                      Obx(() {
                        // 🖼️ 本地头像（上传中）
                        if (controller.isLocalAvatar.value && controller.selectedImagePath.value.isNotEmpty) {
                          return ClipRRect(
                            borderRadius: BorderRadius.circular(30),
                            child: Image.file(
                              File(controller.selectedImagePath.value),
                              width: 60,
                              height: 60,
                              fit: BoxFit.cover,
                            ),
                          );
                        }
                        // 🖼️ 网络头像（使用缓存组件）
                        return CachedAvatar(
                          avatarUrl: controller.userAvatarUrl,
                          size: 60,
                        );
                      }),
                      
                      // 上传进度遮罩
                      Obx(() {
                        if (controller.isUploadingAvatar.value) {
                          return Container(
                            width: 60,
                            height: 60,
                            decoration: BoxDecoration(
                              color: Colors.black.withOpacity(0.5),
                              borderRadius: BorderRadius.circular(30),
                            ),
                            child: const Center(
                              child: CircularProgressIndicator(
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                strokeWidth: 2,
                              ),
                            ),
                          );
                        }
                        return SizedBox.shrink();
                      }),
                    ],
                  ),
                ),
              ),
              SizedBox(width: 8),
              Icon(
                Icons.chevron_right,
                color: Colors.grey,
                size: 20,
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建信息项
  Widget _buildInfoItem({
    required String label,
    required Widget value,
    VoidCallback? onTap,
    bool showArrow = true,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              color: Colors.grey.shade200,
              width: 0.5,
            ),
          ),
        ),
        child: Row(
          children: [
            Text(
              label,
              style: TextStyle(
                fontSize: 16,
                color: Colors.black87,
              ),
            ),
            Expanded(
              child: Align(
                alignment: Alignment.centerRight,
                child: value,
              ),
            ),
            if (showArrow) ...[
              SizedBox(width: 8),
              Icon(
                Icons.chevron_right,
                color: Colors.grey,
                size: 20,
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// 构建爱好区域
  Widget _buildHobbiesSection() {
    return GetBuilder<PeofileDetialController>(
      id: "profile_detial",
      builder: (controller) {
        return Container(
          color: Colors.white,
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '爱好',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.black87,
                ),
              ),
              SizedBox(height: 12),
              Obx(() => Row(
                children: ['吃', '喝', '玩', '乐', '购'].map((hobby) {
                  // 🎯 从 Form 模型获取爱好状态
                  final isSelected = controller.form.value.hobbies.contains(hobby);
                  
                  return Padding(
                    padding: const EdgeInsets.only(right: 10),
                    child: GestureDetector(
                      onTap: () {
                        controller.toggleHobby(hobby);
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                        decoration: BoxDecoration(
                          color: isSelected 
                              ? Color(0xFFCB5050)
                              : Colors.grey[200],
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Text(
                          hobby,
                          style: TextStyle(
                            color: isSelected
                                ? Colors.white
                                : Colors.black87,
                            fontSize: 14,
                          ),
                        ),
                      ),
                    ),
                  );
                }).toList(),
              )),
            ],
          ),
        );
      },
    );
  }

  /// 构建相册区域
  Widget _buildAlbumSection() {
    return GetBuilder<PeofileDetialController>(
      id: "profile_detial",
      builder: (controller) {
        return Container(
          color: Colors.white,
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '相册',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  ),
                  Obx(() {
                    // 🎯 从 Form 模型获取相册图片列表
                    final albumImages = controller.form.value.albumImages;
                    const maxImages = 4;
                    return Text(
                      '${albumImages.length}/$maxImages',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                    );
                  }),
                ],
              ),
              SizedBox(height: 12),
              Obx(() {
                // 🎯 从 Form 模型获取相册图片列表
                final albumImages = controller.form.value.albumImages;
                const maxImages = 4;
                final showAddButton = albumImages.length < maxImages;
                
                return GridView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    crossAxisSpacing: 12,
                    mainAxisSpacing: 12,
                    childAspectRatio: 1.0,
                  ),
                  itemCount: albumImages.length + (showAddButton ? 1 : 0),
                  itemBuilder: (context, index) {
                    if (showAddButton && index == albumImages.length) {
                      return GestureDetector(
                        onTap: () => _showAddAlbumImageOptions(Get.context!, controller),
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(
                              color: Colors.grey[300]!,
                              width: 1,
                              style: BorderStyle.solid,
                            ),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.add,
                                size: 24,
                                color: Colors.grey[600],
                              ),
                              SizedBox(height: 4),
                              Text(
                                '添加照片',
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 10,
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    }
                    
                    final imageUrl = albumImages[index];
                    return GestureDetector(
                      onLongPress: () => _showAlbumImageOptions(Get.context!, controller, index, imageUrl),
                      child: Stack(
                        children: [
                          // 🖼️ 使用缓存图片组件
                          CachedImage(
                            imageUrl: imageUrl,
                            width: double.infinity,
                            height: double.infinity,
                            fit: BoxFit.cover,
                            borderRadius: 8,
                            memCacheWidth: 300,  // 相册缩略图优化
                            memCacheHeight: 300,
                            placeholderColor: Colors.grey[300],
                            errorIcon: Icons.broken_image,
                          ),
                          Positioned(
                            top: 4,
                            right: 4,
                            child: GestureDetector(
                              onTap: () => controller.deleteLocalAlbumImage(index),
                              child: Container(
                                width: 20,
                                height: 20,
                                decoration: BoxDecoration(
                                  color: Colors.red,
                                  shape: BoxShape.circle,
                                ),
                                child: Icon(
                                  Icons.close,
                                  color: Colors.white,
                                  size: 14,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                );
              }),
            ],
          ),
        );
      },
    );
  }

  /// 显示添加相册图片选项
  void _showAddAlbumImageOptions(BuildContext context, PeofileDetialController controller) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: Icon(Icons.camera_alt, color: Color(0xFFCB5050)),
                title: Text('拍照'),
                onTap: () {
                  Navigator.pop(context);
                  controller.pickAlbumImageFromCamera();
                },
              ),
              ListTile(
                leading: Icon(Icons.photo_library, color: Color(0xFFCB5050)),
                title: Text('从相册选择'),
                onTap: () {
                  Navigator.pop(context);
                  controller.pickAlbumImageFromGallery();
                },
              ),
              ListTile(
                leading: Icon(Icons.close, color: Colors.grey),
                title: Text('取消'),
                onTap: () => Navigator.pop(context),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 显示相册图片操作选项
  void _showAlbumImageOptions(BuildContext context, PeofileDetialController controller, int index, String imageUrl) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: Icon(Icons.swap_horiz, color: Color(0xFFCB5050)),
                title: Text('替换图片'),
                onTap: () {
                  Navigator.pop(context);
                  controller.replaceLocalAlbumImage(index);
                },
              ),
              ListTile(
                leading: Icon(Icons.delete_outline, color: Colors.red),
                title: Text('删除图片'),
                onTap: () {
                  Navigator.pop(context);
                  controller.deleteLocalAlbumImage(index);
                },
              ),
              ListTile(
                leading: Icon(Icons.close, color: Colors.grey),
                title: Text('取消'),
                onTap: () => Navigator.pop(context),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 显示编辑对话框
  void _showEditDialog(
    BuildContext context,
    String title,
    String currentValue,
    Function(String) onSave, {
    int maxLines = 1,
  }) {
    final TextEditingController textController = TextEditingController(text: currentValue);

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          child: Padding(
            padding: EdgeInsets.all(20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 16),
                TextField(
                  controller: textController,
                  maxLines: maxLines,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    hintText: '请输入$title',
                  ),
                ),
                SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton(
                      onPressed: () => Navigator.of(context).pop(),
                      child: Text(
                        '取消',
                        style: TextStyle(color: Colors.grey),
                      ),
                    ),
                    SizedBox(width: 12),
                    ElevatedButton(
                      onPressed: () {
                        final newValue = textController.text.trim();
                        if (newValue.isNotEmpty) {
                          onSave(newValue);
                          Navigator.of(context).pop();
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Color(0xFFCB5050),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      child: Text(
                        '保存',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 显示性别选择器
  void _showGenderPicker(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: Text('男', textAlign: TextAlign.center),
                onTap: () {
                  controller.updateLocalGender('男');
                  Navigator.of(context).pop();
                },
              ),
              Divider(height: 1),
              ListTile(
                title: Text('女', textAlign: TextAlign.center),
                onTap: () {
                  controller.updateLocalGender('女');
                  Navigator.of(context).pop();
                },
              ),
              Divider(height: 1),
              ListTile(
                title: Text('未知', textAlign: TextAlign.center),
                onTap: () {
                  controller.updateLocalGender('未知');
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        );
      },
    );
  }

  /// 显示日期选择器
  void _showDatePicker(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.light(
              primary: Color(0xFFCB5050),
              onPrimary: Colors.white,
              onSurface: Colors.black,
            ),
          ),
          child: child!,
        );
      },
    );

    if (picked != null) {
      final formattedDate = '${picked.year}-${picked.month.toString().padLeft(2, '0')}-${picked.day.toString().padLeft(2, '0')}';
      controller.updateLocalBirthday(formattedDate);
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemUIUtils.setTransparentStatusBarDark();
    
    return GetBuilder<PeofileDetialController>(
      init: PeofileDetialController(),
      id: "profile_detial",
      builder: (_) {
        return Scaffold(
          backgroundColor: Colors.grey[100],
          appBar: AppBar(
            title: Text(''),
            backgroundColor: Colors.white,
            foregroundColor: Colors.black87,
            elevation: 0,
            leading: IconButton(
              onPressed: controller.onBackTap,
              icon: const Icon(Icons.arrow_back_ios),
            ),
          ),
          body: _buildView(),
          // 🎯 底部悬浮保存按钮
          bottomNavigationBar: Obx(() {
            // 🎯 从 Form 模型获取变更状态
            if (!controller.hasAnyChanges) {
              return SizedBox.shrink();
            }
            
            return Container(
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    offset: Offset(0, -2),
                    blurRadius: 8,
                  ),
                ],
              ),
              child: SafeArea(
                child: Obx(() => ElevatedButton(
                  onPressed: controller.isSaving.value
                      ? null
                      : controller.saveAllChanges,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFFCB5050),
                    foregroundColor: Colors.white,
                    padding: EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    elevation: 0,
                  ),
                  child: controller.isSaving.value
                      ? Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                              ),
                            ),
                            SizedBox(width: 12),
                            Text(
                              '保存中...',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        )
                      : Text(
                          '保存所有修改',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                )),
              ),
            );
          }),
        );
      },
    );
  }
}
